//
// Created by 28365 on 2025/3/13.
//

#include "../include/config/handler/DefaultUpdaterHandler.h"
#include "../include/exception/UnConnectServerException.h"
#include "../include/utils/VersionUtils.hpp"
#include "config/server_api/result_obj/ReqValue.h"

void DefaultUpdaterHandler::updateStart(UpdateStartEvent &event, const ODUpdater *_odUpdater) {
    this->odUpdater = _odUpdater;

    ReqValue<int> versionR = odUpdater->getUpdaterServer()->getUnpublishedVersion(odUpdater->getUnpublishKey(),*odUpdater);
    if (versionR.getServerApiState() != SUCCESS){
        throw UnConnectServerException("未发布密钥错误");
    }
    unpublishedVersion = versionR.getData();
    odUpdater->getLogger()->debug("内测版本--->[v" + version::intToVersion(unpublishedVersion) + "]");
}

void DefaultUpdaterHandler::updateStartVersion(int version) {
    nowVersion = version;
    if (nowVersion != unpublishedVersion){
        this->odUpdater->getUpdateRecorder()->useVersion(this->odUpdater,version);
    }
}

void DefaultUpdaterHandler::preUpdate(PreUpdateEvent &event) {

}

void DefaultUpdaterHandler::update(const UpdatingEvent &event) {

}

void DefaultUpdaterHandler::postUpdate(const PostUpdateEvent &event) {
    if (nowVersion != unpublishedVersion){
        this->odUpdater->getUpdateRecorder()->addRes(event.getRes()->getId());
    }
}

void DefaultUpdaterHandler::updateError(const UpdateErrorEvent &event) {

}

void DefaultUpdaterHandler::updateDoneVersion(int version) {
    if (nowVersion != unpublishedVersion){
        this->odUpdater->getUpdateRecorder()->complete();
    }
}

void DefaultUpdaterHandler::allUpdateComplete(const UpdateCompleteEvent &event) {
    //出现异常则切断记录器
    if (event.hasError() && nowVersion != unpublishedVersion){
        this->odUpdater->getUpdateRecorder()->closeStream();
    }
}

DefaultUpdaterHandler::~DefaultUpdaterHandler()= default;
